<template>
  <div class="product-container">
    <div class="product-header">
      <h1>商品管理</h1>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        新增商品
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入商品名称"
            clearable
            style="width: 300px;"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="上架" value="active" />
            <el-option label="下架" value="inactive" />
            <el-option label="售罄" value="sold_out" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品表格 -->
    <el-card>
      <el-table :data="productList" v-loading="loading" style="width: 100%">
        <el-table-column prop="product_id" label="ID" width="80" />
        <el-table-column prop="product_name" label="商品名称" min-width="200" />
        <el-table-column prop="anchor.anchor_name" label="主播" width="120">
          <template #default="{ row }">
            {{ row.anchor?.anchor_name || '未知主播' }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">
            ¥{{ row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="stock_quantity" label="库存" width="100" />
        <el-table-column prop="sales_count" label="销量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" type="primary">编辑</el-button>
            <el-button 
              size="small" 
              @click="handleImageManage(row)"
              type="success"
            >
              图片管理
            </el-button>
            <el-button 
              size="small" 
              :type="row.status === 'active' ? 'warning' : 'success'"
              @click="handleToggleStatus(row)"
              :disabled="row.status === 'sold_out'"
            >
              {{ getStatusButtonText(row.status) }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
              :disabled="row.sales_count > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建商品对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      title="创建商品" 
      width="600px"
      @close="handleCreateDialogClose"
    >
      <el-form 
        :model="createForm" 
        :rules="rules" 
        ref="createFormRef" 
        label-width="120px"
      >
        <el-form-item label="商品名称" prop="product_name">
          <el-input 
            v-model="createForm.product_name" 
            placeholder="请输入商品名称"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="商品描述" prop="product_description">
          <el-input
            v-model="createForm.product_description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="createForm.price"
            :min="0.01"
            :max="999999.99"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="原价">
          <el-input-number
            v-model="createForm.original_price"
            :min="0.01"
            :max="999999.99"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock_quantity">
          <el-input-number
            v-model="createForm.stock_quantity"
            :min="0"
            :max="99999"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-input 
            v-model="createForm.category" 
            placeholder="请输入商品分类"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreateSubmit" :loading="creating">创建</el-button>
      </template>
    </el-dialog>

    <!-- 编辑商品对话框 -->
    <el-dialog 
      v-model="showEditDialog" 
      title="编辑商品" 
      width="600px"
      @close="handleEditDialogClose"
    >
      <el-form 
        :model="editForm" 
        :rules="rules" 
        ref="editFormRef" 
        label-width="120px"
      >
        <el-form-item label="商品名称" prop="product_name">
          <el-input 
            v-model="editForm.product_name" 
            placeholder="请输入商品名称"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="商品描述" prop="product_description">
          <el-input
            v-model="editForm.product_description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="editForm.price"
            :min="0.01"
            :max="999999.99"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="原价">
          <el-input-number
            v-model="editForm.original_price"
            :min="0.01"
            :max="999999.99"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock_quantity">
          <el-input-number
            v-model="editForm.stock_quantity"
            :min="0"
            :max="99999"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-input 
            v-model="editForm.category" 
            placeholder="请输入商品分类"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="上架" value="active" />
            <el-option label="下架" value="inactive" />
            <el-option label="售罄" value="sold_out" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit" :loading="editing">保存</el-button>
      </template>
    </el-dialog>

    <!-- 图片管理对话框 -->
    <el-dialog 
      v-model="showImageDialog" 
      :title="`图片管理 - ${currentProduct?.product_name || ''}`" 
      width="800px"
      @close="handleImageDialogClose"
    >
      <div class="image-management">
        <!-- 图片上传 -->
        <div class="upload-section">
          <el-upload
            ref="uploadRef"
            :action="uploadAction"
            :headers="uploadHeaders"
            :data="uploadData"
            :file-list="fileList"
            list-type="picture-card"
            :multiple="true"
            :limit="10"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleRemove"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
            <div class="upload-tip">
              点击上传图片<br/>
              支持jpg、png、gif格式<br/>
              单张图片不超过5MB
            </div>
          </el-upload>
        </div>

        <!-- 图片列表 -->
        <div class="image-list" v-if="productImages.length > 0">
          <h4>已上传图片 (拖拽排序)</h4>
          <draggable 
            v-model="productImages" 
            item-key="image_id"
            @end="handleSortEnd"
            class="image-grid"
          >
            <template #item="{ element: image, index }">
              <div class="image-item" :class="{ 'cover-image': image.image_url === currentProduct?.cover_image }">
                <el-image
                  :src="getFullImageUrl(image.image_url)"
                  fit="cover"
                  class="product-image"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
                <div class="image-actions">
                  <el-button 
                    size="small" 
                    :type="image.image_url === currentProduct?.cover_image ? 'primary' : 'default'"
                    @click="handleSetCover(image)"
                  >
                    {{ image.image_url === currentProduct?.cover_image ? '封面' : '设封面' }}
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click="handleDeleteImage(image)"
                  >
                    删除
                  </el-button>
                </div>
                <div class="image-sort">#{{ index + 1 }}</div>
              </div>
            </template>
          </draggable>
        </div>

        <div class="empty-state" v-else>
          <el-empty description="暂无图片，请上传商品图片" />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showImageDialog = false">关闭</el-button>
        <el-button type="primary" @click="showImageDialog = false">完成</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import { adminAPI } from '../../api/admin'
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'

interface Product {
  product_id: number
  product_name: string
  product_description: string
  price: number
  original_price: number | null
  stock_quantity: number
  category: string
  status: string
  cover_image: string
  sales_count: number
  created_at: string
  updated_at: string
  anchor?: {
    anchor_name: string
  }
  images?: ProductImage[]
}

interface ProductImage {
  image_id: number
  product_id: number
  image_url: string
  sort_order: number
  created_at: string
}

// 响应式数据
const loading = ref(false)
const creating = ref(false)
const editing = ref(false)
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const showImageDialog = ref(false)
const createFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()
const uploadRef = ref()
const currentEditId = ref<number | null>(null)
const currentProduct = ref<Product | null>(null)

const productList = ref<Product[]>([])
const productImages = ref<ProductImage[]>([])
const fileList = ref<UploadUserFile[]>([])

const searchForm = reactive({
  search: '',
  status: ''
})

const createForm = reactive({
  product_name: '',
  product_description: '',
  price: 0.01,
  original_price: null as number | null,
  stock_quantity: 0,
  category: '',
  cover_image: ''
})

const editForm = reactive({
  product_name: '',
  product_description: '',
  price: 0.01,
  original_price: null as number | null,
  stock_quantity: 0,
  category: '',
  status: 'active',
  cover_image: ''
})

const rules: FormRules = {
  product_name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 255, message: '商品名称长度在 1 到 255 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
  ],
  stock_quantity: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存不能为负数', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择商品状态', trigger: 'change' }
  ]
}

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 上传相关配置
const uploadAction = computed(() => {
  if (!currentProduct.value) return ''
  return `http://localhost:3000/api/admin/products/${currentProduct.value.product_id}/images`
})

const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return {
    Authorization: `Bearer ${token}`
  }
})

const uploadData = ref({})

// 加载商品列表
const loadProducts = async () => {
  try {
    loading.value = true
    console.log('📦 加载商品列表...')
    
    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      search: searchForm.search,
      status: searchForm.status
    }
    
    const response = await adminAPI.getProducts(params)
    
    // 兼容不同的响应结构
    let success, data, message
    
    if (response.success !== undefined) {
      success = response.success
      data = response.data
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      data = response.data.data
      message = response.data.message
    } else {
      success = true
      data = response.data || response
      message = '成功'
    }
    
    if (success) {
      productList.value = data?.products || data || []
      pagination.total = data?.pagination?.total || data?.total || productList.value.length
      console.log('✅ 商品列表加载成功，数量:', productList.value.length)
    } else {
      throw new Error(message || '数据加载失败')
    }
    
  } catch (error: any) {
    console.error('❌ 加载商品列表失败:', error)
    ElMessage.error('加载商品列表失败: ' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadProducts()
}

// 重置搜索
const handleReset = () => {
  searchForm.search = ''
  searchForm.status = ''
  pagination.current = 1
  loadProducts()
}

// 新增商品
const handleCreate = () => {
  showCreateDialog.value = true
}

// 创建商品提交
const handleCreateSubmit = async () => {
  if (!createFormRef.value) return
  
  try {
    await createFormRef.value.validate()
    creating.value = true
    
    console.log('🎯 提交创建商品:', createForm)
    
    const response = await adminAPI.createProduct(createForm)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '创建成功'
    }
    
    if (success) {
      ElMessage.success('商品创建成功')
      showCreateDialog.value = false
      resetCreateForm()
      loadProducts()
    } else {
      throw new Error(message || '创建失败')
    }
  } catch (error: any) {
    console.error('❌ 创建商品失败:', error)
    if (error instanceof Error) {
      ElMessage.error('创建失败: ' + error.message)
    }
  } finally {
    creating.value = false
  }
}

// 编辑商品
const handleEdit = async (product: Product) => {
  try {
    console.log('✏️ 开始编辑商品:', product.product_id)
    currentEditId.value = product.product_id
    
    // 直接使用当前行的数据，避免额外的API调用
    Object.assign(editForm, {
      product_name: product.product_name,
      product_description: product.product_description || '',
      price: product.price,
      original_price: product.original_price,
      stock_quantity: product.stock_quantity,
      category: product.category || '',
      status: product.status,
      cover_image: product.cover_image || ''
    })
    
    showEditDialog.value = true
    console.log('✅ 商品数据填充成功')
  } catch (error: any) {
    console.error('❌ 加载商品详情失败:', error)
    ElMessage.error('加载商品详情失败: ' + (error.message || '网络错误'))
  }
}

// 编辑商品提交
const handleEditSubmit = async () => {
  if (!editFormRef.value || !currentEditId.value) return
  
  try {
    await editFormRef.value.validate()
    editing.value = true
    
    console.log('💾 提交编辑商品:', currentEditId.value, editForm)
    
    const response = await adminAPI.updateProduct(currentEditId.value, editForm)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '更新成功'
    }
    
    if (success) {
      ElMessage.success('商品更新成功')
      showEditDialog.value = false
      resetEditForm()
      loadProducts()
    } else {
      throw new Error(message || '更新失败')
    }
  } catch (error: any) {
    console.error('❌ 更新商品失败:', error)
    if (error instanceof Error) {
      ElMessage.error('更新失败: ' + error.message)
    }
  } finally {
    editing.value = false
  }
}

// 图片管理
const handleImageManage = async (product: Product) => {
  try {
    currentProduct.value = product
    console.log('🖼️ 开始管理商品图片:', product.product_id)
    
    // 加载商品详情获取图片列表
    const response = await adminAPI.getProductById(product.product_id)
    
    let success, data
    
    if (response.success !== undefined) {
      success = response.success
      data = response.data
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      data = response.data.data
    } else {
      success = true
      data = response.data || response
    }
    
    if (success) {
      productImages.value = data.images || []
      // 按排序字段排序
      productImages.value.sort((a, b) => a.sort_order - b.sort_order)
      showImageDialog.value = true
      console.log('✅ 商品图片加载成功:', productImages.value.length)
    } else {
      throw new Error('加载商品图片失败')
    }
  } catch (error: any) {
    console.error('❌ 加载商品图片失败:', error)
    ElMessage.error('加载商品图片失败: ' + (error.message || '网络错误'))
  }
}

// 删除商品
const handleDelete = async (product: Product) => {
  try {
    await ElMessageBox.confirm(
      `确定删除商品 "${product.product_name}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    console.log('🗑️ 开始删除商品:', product.product_id)
    
    const response = await adminAPI.deleteProduct(product.product_id)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '删除成功'
    }
    
    if (success) {
      ElMessage.success('商品删除成功')
      loadProducts()
    } else {
      throw new Error(message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('❌ 删除商品失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '网络错误'))
    }
  }
}

// 上下架商品
const handleToggleStatus = async (product: Product) => {
  try {
    const newStatus = product.status === 'active' ? 'inactive' : 'active'
    const action = newStatus === 'active' ? '上架' : '下架'
    
    await ElMessageBox.confirm(
      `确定要${action}商品 "${product.product_name}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log(`🔄 ${action}商品:`, product.product_id, newStatus)
    
    // 调用API更新商品状态
    const response = await adminAPI.updateProductStatus(product.product_id, newStatus)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '状态更新成功'
    }
    
    if (success) {
      ElMessage.success(`${action}成功`)
      // 重新加载列表
      loadProducts()
    } else {
      throw new Error(message || `${action}失败`)
    }
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('❌ 更新商品状态失败:', error)
      ElMessage.error('操作失败: ' + (error.message || '网络错误'))
    }
  }
}

// 图片上传相关方法
const handleExceed: UploadProps['onExceed'] = (files) => {
  ElMessage.warning(`最多只能上传 10 张图片，当前选择了 ${files.length} 张`)
}

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const handleUploadSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.success) {
    ElMessage.success('图片上传成功')
    // 重新加载图片列表
    if (currentProduct.value) {
      handleImageManage(currentProduct.value)
    }
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleUploadError: UploadProps['onError'] = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('图片上传失败')
}

const handleRemove: UploadProps['onRemove'] = async (file) => {
  try {
    // 这里可以添加删除逻辑，如果需要的话
    console.log('移除文件:', file)
  } catch (error) {
    console.error('移除文件失败:', error)
  }
}

// 删除图片
const handleDeleteImage = async (image: ProductImage) => {
  try {
    await ElMessageBox.confirm(
      '确定删除这张图片吗？',
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await adminAPI.deleteProductImage(image.image_id)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '删除成功'
    }
    
    if (success) {
      ElMessage.success('图片删除成功')
      // 从本地列表中移除
      productImages.value = productImages.value.filter(img => img.image_id !== image.image_id)
    } else {
      throw new Error(message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除图片失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '网络错误'))
    }
  }
}

// 设置封面
const handleSetCover = async (image: ProductImage) => {
  try {
    const response = await adminAPI.setProductCover(image.image_id)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '设置成功'
    }
    
    if (success) {
      ElMessage.success('封面设置成功')
      // 更新当前商品的封面
      if (currentProduct.value) {
        currentProduct.value.cover_image = image.image_url
      }
    } else {
      throw new Error(message || '设置失败')
    }
  } catch (error: any) {
    console.error('设置封面失败:', error)
    ElMessage.error('设置失败: ' + (error.message || '网络错误'))
  }
}

// 图片排序
const handleSortEnd = async () => {
  try {
    const imageIds = productImages.value.map(img => img.image_id)
    const response = await adminAPI.sortProductImages(currentProduct.value!.product_id, imageIds)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '排序成功'
    }
    
    if (success) {
      ElMessage.success('图片排序已保存')
    } else {
      throw new Error(message || '排序失败')
    }
  } catch (error: any) {
    console.error('图片排序失败:', error)
    ElMessage.error('排序失败: ' + (error.message || '网络错误'))
    // 重新加载恢复原顺序
    if (currentProduct.value) {
      handleImageManage(currentProduct.value)
    }
  }
}

// 获取完整图片URL
const getFullImageUrl = (url: string) => {
  if (url.startsWith('http')) {
    return url
  }
  return `http://localhost:3000${url}`
}

// 重置创建表单
const resetCreateForm = () => {
  Object.assign(createForm, {
    product_name: '',
    product_description: '',
    price: 0.01,
    original_price: null,
    stock_quantity: 0,
    category: '',
    cover_image: ''
  })
  createFormRef.value?.clearValidate()
}

// 重置编辑表单
const resetEditForm = () => {
  Object.assign(editForm, {
    product_name: '',
    product_description: '',
    price: 0.01,
    original_price: null,
    stock_quantity: 0,
    category: '',
    status: 'active',
    cover_image: ''
  })
  currentEditId.value = null
  editFormRef.value?.clearValidate()
}

// 重置图片管理
const handleImageDialogClose = () => {
  currentProduct.value = null
  productImages.value = []
  fileList.value = []
}

// 对话框关闭处理
const handleCreateDialogClose = () => {
  resetCreateForm()
}

const handleEditDialogClose = () => {
  resetEditForm()
}

// 状态显示工具函数
const getStatusType = (status: string) => {
  const types: { [key: string]: string } = {
    active: 'success',
    inactive: 'info',
    sold_out: 'warning'
  }
  return types[status] || ''
}

const getStatusText = (status: string) => {
  const texts: { [key: string]: string } = {
    active: '上架',
    inactive: '下架',
    sold_out: '售罄'
  }
  return texts[status] || status
}

const getStatusButtonText = (status: string) => {
  const texts: { [key: string]: string } = {
    active: '下架',
    inactive: '上架',
    sold_out: '售罄'
  }
  return texts[status] || '操作'
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  loadProducts()
}

// 页码变化
const handleCurrentChange = (page: number) => {
  pagination.current = page
  loadProducts()
}

// 格式化日期
const formatDate = (date: string | Date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
.product-container {
  padding: 20px;
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 图片管理样式 */
.image-management {
  max-height: 60vh;
  overflow-y: auto;
}

.upload-section {
  margin-bottom: 20px;
}

.upload-tip {
  font-size: 12px;
  color: #666;
  text-align: center;
  line-height: 1.4;
}

.image-list h4 {
  margin-bottom: 10px;
  color: #333;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.image-item {
  position: relative;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.image-item:hover {
  border-color: #409eff;
  transform: translateY(-2px);
}

.image-item.cover-image {
  border-color: #67c23a;
  border-width: 3px;
}

.product-image {
  width: 100%;
  height: 120px;
  display: block;
}

.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  padding: 8px;
  display: flex;
  justify-content: space-around;
}

.image-sort {
  position: absolute;
  top: 5px;
  left: 5px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}
</style>